<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col
            :md="4"
            :sm="12">
            <a-form-item label="菜单分组">
              <a-select v-model="queryParam.group_id">
                <a-select-option
                  v-for="(item, key) in groupList"
                  :key="'groupId_' + key"
                  :value="item.group_id">{{ item.group_name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="12">
            <a-form-item label="名称">
              <a-input v-model="queryParam.name" placeholder="请输入搜素关键字"/>
            </a-form-item>
          </a-col>
          <a-col
            :md="4"
            :sm="12">
            <span class="table-page-search-submitButtons">
              <a-button
                type="primary"
                @click="loadTreeList">查询</a-button>
              <a-button style="margin-left: 8px" @click="queryParam.name = '';loadTreeList();">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button
        v-if="$auth('admin.sys-menu.save')"
        type="primary"
        icon="plus"
        @click="$refs.createModal.add()">新建</a-button>
      <a-alert style="margin-top:10px;" message="操作指引" type="success">
        <p slot="description">
          鼠标按住菜单拖拽可实现<span style="color: red">快速排序</span>和<span style="color: red">结构变更</span>。
        </p>
      </a-alert>
    </div>
    <a-tree
      v-if="treeData.length"
      showLine
      :draggable="$auth('admin.sys-menu.set-order')"
      defaultExpandAll
      @drop="onDrop"
      :treeData="treeData"
      :replaceFields="{children:'children', title:'menu_name', key:'menu_id' }">
      <template
        slot="custom"
        slot-scope="item">
        <a-icon :type="item.icon" />
        <span style="margin-right: 300px;">{{ item.menu_name }}</span>
        <a-tag color="#2db7f5">排序:{{ item.order_num }}</a-tag>
        <a-button
          size="small"
          icon="plus"
          type="primary"
          v-if="$auth('admin.sys-menu.save')"
          @click="$refs.createModal.addChild(item)">添加子菜单</a-button>
        <a-divider
          v-if="$auth('admin.sys-menu.save')"
          type="vertical" />
        <a-button
          size="small"
          icon="edit"
          type="primary"
          v-if="$auth('admin.sys-menu.save')"
          @click="$refs.createModal.edit(item)">编辑</a-button>
        <a-divider
          v-if="$auth('admin.sys-menu.destroy')"
          type="vertical" />
        <a-button
          size="small"
          icon="delete"
          type="danger"
          v-if="('admin.sys-menu.destroy')"
          @click="remove(item)">删除</a-button>
      </template>
    </a-tree>
    <create-form
      ref="createModal"
      :groupId="queryParam.group_id"
      :treePermData="permList"
      @ok="loadTreeList" />
  </a-card>
</template>

<script>
import CreateForm from './modules/SysMenuCreateForm'
import { loadList, delData, setOrder } from '@/api/system/sysmenu'

const menuFormatter = (list) => {
  if (list === null) return []
  const re = list.map(
    (item) => {
      item.scopedSlots = { 'title': 'custom' }
      if (item.children != null) {
        item.children = menuFormatter(item.children)
      }
      return item
    }
  )
  return re
}
const permFormatter = (list) => {
  if (list === null) return []
  const re = list.map(
    (item) => {
      const result = {
        children: [],
        value: item.perm_id,
        title: item.display_name,
        parent_id: item.parent_id
      }
      if (item.children != null) {
        result.children = permFormatter(item.children)
      }
      return result
    }
  )
  return re
}

export default {
  name: 'SysMenu',
  data () {
    return {
      // 查询参数
      queryParam: {
        group_id: 1,
        name: ''
      },
      treeData: [],
      groupList: [],
      permList: []
    }
  },
  components: {
    CreateForm
  },
  created () {
    this.loadTreeList()
  },
  methods: {
    loadTreeList: function () {
      loadList(this.queryParam).then(res => {
        if (res.code === 0) {
          this.treeData = menuFormatter(res.data.menuList)
          this.groupList = res.data.groupList
          this.permList = permFormatter(res.data.permList)
        }
      })
    },
    onDrop (info) {
      const dropPos = info.node.pos.split('-')
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
      let dropType = ''
      if (dropPosition === 1) {
        dropType = 'after'
      } else if (dropPosition === -1) {
        dropType = 'before'
      } else if (dropPosition === 0) {
        dropType = 'inner'
      }
      setOrder(info.dragNode.dataRef, info.node.dataRef, dropType).then(response => {
        if (response.code === 0) {
          this.$message.success(response.message)
        } else {
          this.$message.error(response.message)
        }
        // 重新加载数据
        this.loadTreeList()
      })
    },
    remove (data) { // 删除
      if (!data) {
        this.$message.error('请选中您想要删除的菜单')
        return false
      }
      this.$confirm({
        title: '你确定要删除该菜单？',
        content: '操作将永久删除该菜单, 是否继续?',
        onOk: () => {
          return delData([data.menu_id]).then(res => {
            if (res.code === 0) {
              this.$message.success(
                '删除菜单成功'
              )
              // 重新加载菜单数据
              this.loadTreeList()
            }
          }).catch((error) => console.error(error))
        },
        onCancel () {
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.custom-tree-node {
  height: 100px;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
